#!/bin/bash

INPUTFILE=$1
ROOTDIR=$2
DESTGIT=$3
USER=$4
TOKEN=$5

OLDIFS=$IFS
IFS=";"

[ ! -f $INPUTFILE ] && { echo "$INPUTFILE file not found"; exit 99; }
[ ! -d $ROOTDIR ] && { echo "$ROOTDIR directory not found"; exit 99; }

while read prj src
do
	if [ ! -d "$ROOTDIR/$prj" ]; then
		cd $ROOTDIR
		echo "Cloning repos $src to $ROOTDIR/$prj"
		git clone --mirror $src $prj
		cd $ROOTDIR/$prj
		echo "Create new repos $DESTGIT/$USER/$prj.git"
		curl -X POST -H 'Content-Type: application/json' -H 'Authorization: Bearer $TOKEN' "$DESTGIT/api/v4/projects/" -d '{"name":$prj,"path":$prj,"description":"Forked from $src","private":false}'
		git remote add upstream "$DESTGIT/$USER/$prj.git"
		git fetch -p origin
		git push --all upstream
	else
		echo "Update repos $DESTGIT/$USER/$prj.git"
		cd $ROOTDIR/$prj
        	git fetch -p origin
        	git fetch upstream
        	git push --all upstream
	fi

	cd ..

done < $INPUTFILE

IFS=$OLDIFS
